<?php

namespace App\Http\Controllers\Mobile;

use App\Http\Controllers\Controller;
use App\Models\Cart;
use App\Models\Item;
use Illuminate\Support\Facades\Auth;

class CartController extends Controller
{
    //
    public function index()
    {

        $shops = Cart::with(['items'=>function($query){
            return $query->where('uid', $this->uid);
        }])->where('uid', $this->uid)->groupBy('shop_id')
            ->get(['id', 'uid', 'shop_id', 'shop_name'])
        ->map(function ($shop){
            $shop->items = $shop->items->map(function ($item){
                $item->thumb = image_url($item->thumb);
                $item->image = image_url($item->image);
                return $item;
            });
            return $shop;
        });

        $items = Item::onSale()->limit(20)->orderByRaw('RAND()')->get();
        $this->assign(compact('shops', 'items'));
        return $this->view('mobile.cart');
    }

    public function add()
    {
        $itemid = $this->request->input('itemid');
        $quantity = $this->request->input('quantity');
        $item = addToCart(Auth::id(), $itemid, $quantity);
        return ajaxReturn(['item'=>$item]);
    }
}
